const fs = require("fs");
const path = require("path");
const { isDocxFile, readDocxFile } = require("./docx");
const { genPdfFile, isPdfFile, readPdfFileText } = require("./pdfFile");

// 指定输入目录和输出文件路径
const inputDir = "../../script/钞能力毛毛"; // 替换为你的目录路径
const outputFile = inputDir + ".pdf"; // 替换为输出文件路径

// 确保输出目录存在
fs.mkdirSync(path.dirname(outputFile), { recursive: true });

async function mergeFiles(directory, outputFile) {
  try {
    const files = fs.readdirSync(directory); // 读取目录下的文件
    const contentList = [];
    for (const file of files) {
      const filePath = path.join(directory, file);
      if (fs.statSync(filePath).isFile()) {
        let content = "";
        // 确保是文件
        if (isDocxFile(filePath)) {
          content = await readDocxFile(filePath);
        } else if (isPdfFile(filePath)) {
          content = await readPdfFileText(filePath);
        } else {
          content = fs.readFileSync(filePath, "utf-8");
        }
        contentList.push({
          name: path.basename(file).split(".")[0],
          content,
        });
      }
    }

    genPdfFile(outputFile, contentList);
  } catch (error) {
    console.error("文件合并过程中发生错误:", error);
  }
}

// 调用函数
mergeFiles(inputDir, outputFile);
